<template>
  <view class="erban-container">
    <!-- 头部信息 -->
    <view class="header-section">
      <view class="title-box">
        <uni-title type="h2" title="二班业务员信息"></uni-title>
        <view class="subtitle">查看当天在多个房间工作的业务员记录</view>
      </view>
    </view>

    <!-- 搜索区域 -->
    <view class="search-section">
      <view class="search-content">
        <view class="search-row">
          <view class="search-item">
            <text class="label">房间号</text>
            <view class="input-wrapper">
              <uni-icons type="home" size="18" color="#909399"></uni-icons>
              <input 
                type="text"
                class="search-input" 
                v-model="searchParams.roomId" 
                placeholder="请输入房间号搜索"
              />
            </view>
          </view>
          <view class="search-item">
            <text class="label">日期</text>
            <view class="input-wrapper">
              <uni-icons type="calendar" size="18" color="#909399"></uni-icons>
              <picker 
                mode="date" 
                :value="searchParams.date" 
                @change="onDateChange"
              >
                <view class="picker-value">{{ searchParams.date || '请选择日期' }}</view>
              </picker>
            </view>
          </view>
        </view>
        <view class="button-group">
          <button class="action-btn reset-btn" @click="handleReset">
            <uni-icons type="refresh" size="16" color="#909399"></uni-icons>
            <text>重置</text>
          </button>
          <button class="action-btn search-btn" @click="handleSearch">
            <uni-icons type="search" size="16" color="#ffffff"></uni-icons>
            <text>搜索</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="stats-section" v-if="roomRecords.length > 0">
      <view class="stats-card">
        <view class="stats-item">
          <text class="stats-number">{{ visibleRecordsCount }}</text>
          <text class="stats-label">二班业务员数</text>
        </view>
        <view class="stats-item">
          <text class="stats-number">{{ totalRooms }}</text>
          <text class="stats-label">涉及房间数</text>
        </view>
        <view class="stats-item">
          <text class="stats-number">{{ totalRoomCount }}</text>
          <text class="stats-label">总房间记录</text>
        </view>
      </view>
    </view>

    <!-- 记录列表 -->
    <view class="records-section">
      <view v-if="loading" class="loading">
        <uni-icons type="spinner-cycle" size="24" color="#409EFF"></uni-icons>
        <text>加载中...</text>
      </view>
      <view v-else-if="roomRecords.length === 0" class="no-data">
        <uni-icons type="info" size="24" color="#909399"></uni-icons>
        <text>暂无当天二班业务员记录</text>
      </view>
      <view v-else>
        <view v-for="(businessUser, index) in roomRecords" :key="businessUser.userId" class="record-item" :style="{ animationDelay: index * 0.1 + 's' }" :class="{ 'hidden': hiddenRecords.includes(businessUser.userId) }">
          <view class="record-header">
            <view class="user-info">
              <text class="user-name">{{ businessUser.userName }}</text>
              <text class="user-details">({{ businessUser.employeeId || '无工号' }} | {{ businessUser.level || '无等级' }})</text>
            </view>
            <view class="status-badge">
              <text>二班业务员</text>
            </view>
          </view>
          
          <view class="record-content">
            <view class="content-row">
              <text class="label">工作房间数:</text>
              <text class="value">{{ businessUser.roomCount }} 个房间</text>
            </view>
            
            <view class="rooms-section">
              <text class="section-title">工作房间详情:</text>
              <view v-for="(room, roomIndex) in businessUser.rooms" :key="roomIndex" class="room-item">
                <view class="room-header">
                  <text class="room-name">{{ room.roomName || `房间${room.roomId}` }}</text>
                  <text class="room-id">(ID: {{ room.roomId }})</text>
                </view>
                <view class="room-details">
                  <view class="detail-row" v-if="room.price">
                    <text class="detail-label">价格:</text>
                    <text class="detail-value">¥{{ room.price }}</text>
                  </view>
                  <view class="detail-row" v-if="room.purpose">
                    <text class="detail-label">用途:</text>
                    <text class="detail-value">{{ room.purpose }}</text>
                  </view>
                  <view class="detail-row" v-if="room.startTime">
                    <text class="detail-label">开始时间:</text>
                    <text class="detail-value">{{ formatDateTime(room.startTime) }}</text>
                  </view>
                  <view class="detail-row" v-if="room.endTime">
                    <text class="detail-label">结束时间:</text>
                    <text class="detail-value">{{ formatDateTime(room.endTime) }}</text>
                  </view>
                  <view class="detail-row" v-if="room.totalAmount">
                    <text class="detail-label">总金额:</text>
                    <text class="detail-value amount">¥{{ room.totalAmount }}</text>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 已统计按钮 -->
            <view class="action-section">
              <button class="counted-btn" @click="markAsCounted(businessUser.userId)">
                <uni-icons type="checkmarkempty" size="16" color="#ffffff"></uni-icons>
                <text>已统计</text>
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { searchNotOneRoomRecord } from '@/api/system/room'

export default {
  data() {
    return {
      roomRecords: [],
      loading: true,
      searchParams: {
        roomId: '',
        date: this.getCurrentDate() // 默认设置为当天日期
      },
      hiddenRecords: [] // 存储已隐藏的记录ID
    }
  },
  computed: {
    // 计算可见记录数量
    visibleRecordsCount() {
      return this.roomRecords.filter(record => !this.hiddenRecords.includes(record.userId)).length
    },
    // 计算涉及的房间数量（去重）
    totalRooms() {
      const rooms = new Set()
      this.roomRecords.forEach(businessUser => {
        if (businessUser.rooms && businessUser.rooms.length > 0) {
          businessUser.rooms.forEach(room => {
            rooms.add(room.roomId)
          })
        }
      })
      return rooms.size
    },
    // 计算总房间记录数
    totalRoomCount() {
      let count = 0
      this.roomRecords.forEach(businessUser => {
        if (businessUser.rooms && businessUser.rooms.length > 0) {
          count += businessUser.rooms.length
        }
      })
      return count
    }
  },
  onLoad() {
    this.hiddenRecords = [] // 确保初始进入页面时清空隐藏记录
    this.fetchRecords()
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.fetchRecords().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  methods: {
    // 获取当前日期
    getCurrentDate() {
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    async fetchRecords() {
      this.loading = true
      try {
        // 构建查询参数，包含日期过滤
        const params = {
          date: this.searchParams.date
        }
        
        // 如果有房间号，也加入查询条件
        if (this.searchParams.roomId) {
          params.roomId = this.searchParams.roomId
        }
        
        const res = await searchNotOneRoomRecord(params)
        if (res.code === 200 && Array.isArray(res.data)) {
          // 直接使用返回的数据，新的数据结构已经是按业务员分组的
          this.roomRecords = res.data
          // 每次获取新数据时清空隐藏记录，确保初始显示所有记录
          this.hiddenRecords = []
        } else {
          this.roomRecords = []
          uni.showToast({ title: res.msg || '查询失败', icon: 'none' })
        }
      } catch (e) {
        this.roomRecords = []
        uni.showToast({ title: '网络异常', icon: 'none' })
      } finally {
        this.loading = false
      }
    },
    
    // 搜索功能
    handleSearch() {
      this.hiddenRecords = [] // 搜索时清空隐藏记录
      this.fetchRecords()
    },
    
    // 重置搜索
    handleReset() {
      this.searchParams = {
        roomId: '',
        date: this.getCurrentDate() // 重置为当天日期
      }
      this.hiddenRecords = [] // 清空隐藏记录
      this.fetchRecords()
    },
    
    // 日期选择
    onDateChange(e) {
      this.searchParams.date = e.detail.value
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    
    // 格式化日期时间
    formatDateTime(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    
    // 标记为已统计
    markAsCounted(userId) {
      if (!this.hiddenRecords.includes(userId)) {
        this.hiddenRecords.push(userId)
      }
      uni.showToast({
        title: '已标记为统计完成',
        icon: 'success',
        duration: 1500
      })
    }
  }
}
</script>

<style lang="scss" scoped>
page {
  background-color: #f5f7fa;
}

.erban-container {
  padding: 30rpx;
  min-height: 100vh;
}

.header-section {
  margin-bottom: 30rpx;
  
  .title-box {
    text-align: center;
    padding: 20rpx 0;
    
    :deep(.uni-title) {
      margin-bottom: 0;
      
      .uni-title__text {
        font-size: 36rpx;
        font-weight: 600;
        color: #303133;
      }
    }
    
    .subtitle {
      font-size: 24rpx;
      color: #909399;
      margin-top: 8rpx;
    }
  }
}

.search-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);

  .search-content {
    .search-row {
      display: flex;
      gap: 20rpx;
      margin-bottom: 24rpx;

      .search-item {
        flex: 1;
        margin-bottom: 0;

        .label {
          display: block;
          font-size: 26rpx;
          color: #606266;
          margin-bottom: 12rpx;
          font-weight: 500;
        }

        .input-wrapper {
          display: flex;
          align-items: center;
          background: #f8f9fa;
          border-radius: 8rpx;
          border: 1px solid #dcdfe6;
          padding: 0 20rpx;
          height: 72rpx;
          transition: all 0.3s ease;

          &:focus-within {
            border-color: #409EFF;
            box-shadow: 0 0 0 2px rgba(64,158,255,0.1);
          }

          .uni-icons {
            margin-right: 12rpx;
          }

          .search-input {
            flex: 1;
            height: 100%;
            font-size: 28rpx;
            color: #303133;
            background: transparent;
            border: none;
            padding: 0;

            &::placeholder {
              color: #909399;
            }
          }

          .picker-value {
            flex: 1;
            height: 100%;
            line-height: 72rpx;
            font-size: 28rpx;
            color: #303133;
            background: transparent;
          }
        }
      }
    }

    .button-group {
      display: flex;
      justify-content: center;
      gap: 24rpx;

      .action-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        min-width: 180rpx;
        height: 72rpx;
        font-size: 28rpx;
        padding: 0 32rpx;
        border-radius: 8rpx;
        border: none;
        transition: all 0.3s ease;

        .uni-icons {
          margin-right: 8rpx;
        }

        &.reset-btn {
          background: #f4f4f5;
          color: #909399;

          &:active {
            background: #e9e9eb;
          }
        }

        &.search-btn {
          background: #409EFF;
          color: #fff;

          &:active {
            background: #66b1ff;
          }
        }
      }
    }
  }
}

.stats-section {
  margin-bottom: 30rpx;
  
  .stats-card {
    background: linear-gradient(135deg, #409EFF 0%, #67C23A 100%);
    border-radius: 16rpx;
    padding: 30rpx;
    display: flex;
    justify-content: space-around;
    box-shadow: 0 4rpx 20rpx rgba(64, 158, 255, 0.3);
    
    .stats-item {
      text-align: center;
      
      .stats-number {
        display: block;
        font-size: 36rpx;
        font-weight: bold;
        color: #fff;
        margin-bottom: 8rpx;
      }
      
      .stats-label {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.9);
      }
    }
  }
}

.records-section {
  .loading, .no-data {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60rpx 0;
    color: #909399;
    font-size: 28rpx;
    
    .uni-icons {
      margin-bottom: 20rpx;
    }
  }
  
  .record-item {
    background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.05);
    transform: translateY(0);
    transition: all 0.3s ease;
    animation: slideIn 0.5s ease forwards;
    opacity: 0;
    
    &:active {
      transform: translateY(2rpx);
      box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
    }
    
    .record-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20rpx;
      padding-bottom: 20rpx;
      border-bottom: 1px solid #ebeef5;
      
      .user-info {
        display: flex;
        flex-direction: column;
        gap: 8rpx;
        
        .user-name {
          font-size: 32rpx;
          font-weight: 600;
          color: #303133;
        }
        
        .user-details {
          font-size: 26rpx;
          color: #909399;
        }
      }
      
      .status-badge {
        background: linear-gradient(135deg, #E6A23C 0%, #F56C6C 100%);
        color: #fff;
        padding: 8rpx 16rpx;
        border-radius: 8rpx;
        font-size: 24rpx;
        font-weight: 500;
      }
    }
    
    .record-content {
      .content-row {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 16rpx;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          font-size: 28rpx;
          color: #606266;
          font-weight: 500;
          min-width: 120rpx;
          flex-shrink: 0;
        }
        
        .value {
          font-size: 28rpx;
          color: #303133;
          text-align: right;
          flex: 1;
          margin-left: 20rpx;
          
          &.amount {
            color: #E6A23C;
            font-weight: 600;
          }
        }
      }
      
      .action-section {
        display: flex;
        justify-content: flex-end;
        margin-top: 20rpx;
        padding-top: 20rpx;
        border-top: 1px solid #ebeef5;
        
        .counted-btn {
          display: flex;
          align-items: center;
          justify-content: center;
          background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
          color: #fff;
          border: none;
          border-radius: 8rpx;
          padding: 12rpx 24rpx;
          font-size: 26rpx;
          font-weight: 500;
          transition: all 0.3s ease;
          box-shadow: 0 2rpx 8rpx rgba(103, 194, 58, 0.3);
          min-width: 120rpx;
          
          .uni-icons {
            margin-right: 8rpx;
          }
          
          &:active {
            transform: translateY(1rpx);
            box-shadow: 0 1rpx 4rpx rgba(103, 194, 58, 0.3);
          }
        }
      }
      
      .rooms-section {
        margin-top: 20rpx;
        
        .section-title {
          display: block;
          font-size: 28rpx;
          color: #606266;
          font-weight: 500;
          margin-bottom: 16rpx;
        }
        
        .room-item {
          background: #f8f9fa;
          border-radius: 12rpx;
          padding: 20rpx;
          margin-bottom: 16rpx;
          border-left: 4rpx solid #409EFF;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .room-header {
            display: flex;
            align-items: center;
            gap: 12rpx;
            margin-bottom: 16rpx;
            
            .room-name {
              font-size: 28rpx;
              font-weight: 600;
              color: #303133;
            }
            
            .room-id {
              font-size: 24rpx;
              color: #909399;
            }
          }
          
          .room-details {
            .detail-row {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8rpx;
              
              &:last-child {
                margin-bottom: 0;
              }
              
              .detail-label {
                font-size: 26rpx;
                color: #606266;
                min-width: 120rpx;
                flex-shrink: 0;
              }
              
              .detail-value {
                font-size: 26rpx;
                color: #303133;
                text-align: right;
                flex: 1;
                margin-left: 20rpx;
                
                &.amount {
                  color: #E6A23C;
                  font-weight: 600;
                }
              }
            }
          }
        }
      }
    }
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 隐藏样式
.hidden {
  display: none !important;
}
</style>
